package config

import (
	"fmt"
	"io"
	"net"
	"os"
)

func LoadConfig() {

}

func Start() {
	fmt.Println("Recv File is Starting...")
	listen, err := net.Listen("tcp", ":9233") //监听本地端口
	AssertError(err)
	defer listen.Close()

	for {
		conn, e1 := listen.Accept()
		AssertError(e1)
		go handler(conn) //新协程处理连接
	}
}

func handler(conn net.Conn) {
	fileName := createFile(conn)
	writeFile(fileName, conn)
	defer conn.Close()
}

func createFile(conn net.Conn) string {
	buf := make([]byte, 4*1024)
	n, e2 := conn.Read(buf)
	AssertError(e2)
	fileName := string(buf[:n])
	fmt.Println("Get a file =", fileName, " From: ", conn.RemoteAddr())
	conn.Write([]byte("ok"))
	return fileName
}

func writeFile(fileName string, conn net.Conn) {
	file, e4 := os.Create(fileName)
	AssertError(e4)

	buf := make([]byte, 4*1024)
	for {
		n, e3 := conn.Read(buf)
		if e3 == io.EOF || n == 0 {
			fmt.Println("Recv File finished")
			return
		}
		AssertError(e3)
		file.Write(buf[:n])
	}
	defer file.Close()
}

func AssertError(e error) {
	if e != nil {
		fmt.Println("AssertError Exception: ", e)
		return
	}
}
